<template>
    <div class="summary-screen" :style="{ backgroundImage: `url(${bgUrl})` }">
        <div class="blur-overlay"></div>
        
        <header class="topbar">
            <button class="icon-btn back-btn" aria-label="back" @click="backToHome">
                <svg viewBox="0 0 24 24" width="24" height="24">
                    <path fill="currentColor" d="M15.41 7.41 14 6l-6 6 6 6 1.41-1.41L10.83 12z"/>
                </svg>
            </button>
            <h1 class="page-title">小结</h1>
            <button class="icon-btn" aria-label="view" @click="noop">
                <svg viewBox="0 0 24 24" width="24" height="24">
                    <path fill="currentColor" d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/>
                </svg>
            </button>
        </header>
        
        <main class="summary-content">
            <!-- 提示信息 -->
            <div class="tip-banner">
                <svg viewBox="0 0 24 24" width="20" height="20" class="tip-icon">
                    <path fill="currentColor" d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"/>
                </svg>
                <span>快速回顾本组单词吧~</span>
            </div>
            
            <!-- 单词列表 -->
            <div class="word-list" v-if="wordList.length > 0">
                <div 
                    v-for="(word, index) in wordList" 
                    :key="word.wordId || index"
                    class="word-item"
                    @click="viewWordDetail(word)"
                >
                    <div class="word-text">{{ word.word }}</div>
                    <div class="review-interval">{{ formatReviewInterval(word.nextReviewAt) }}</div>
                </div>
            </div>
            
            <!-- 加载状态 -->
            <div class="loading" v-if="isLoading">
                <div class="loading-text">加载中...</div>
            </div>
            
            <!-- 空状态 -->
            <div class="empty-state" v-if="!isLoading && wordList.length === 0">
                <div class="empty-text">暂无单词数据</div>
            </div>
        </main>
        
        <footer class="footer">
            <div class="progress-info">
                <span>已{{ mode === 'learn' ? '学习' : '复习' }}{{ completedCount }}词,还剩{{ remainingCount }}词</span>
            </div>
            <button class="continue-btn" @click="continueStudy">
                {{ mode === 'learn' ? '继续学习' : '继续复习' }}
            </button>
        </footer>
        
        <!-- 单词详情弹窗 -->
        <div class="word-detail-modal" v-if="selectedWord" @click.self="closeWordDetail">
            <div class="modal-content">
                <button class="close-btn" @click="closeWordDetail">×</button>
                <div class="modal-word">{{ selectedWord.word }}</div>
                <div class="modal-phonetic" v-if="selectedWord.phonetic">{{ selectedWord.phonetic }}</div>
                <div class="modal-meaning">
                    <span class="modal-part-of-speech" v-if="selectedWord.partOfSpeech">{{ selectedWord.partOfSpeech }}</span>
                    <span class="modal-meaning-text">{{ selectedWord.correctMeaning }}</span>
                </div>
                <div class="modal-example" v-if="selectedWord.exampleSentenceEn || selectedWord.exampleSentenceCn">
                    <div class="modal-example-en" v-if="selectedWord.exampleSentenceEn">{{ selectedWord.exampleSentenceEn }}</div>
                    <div class="modal-example-cn" v-if="selectedWord.exampleSentenceCn">{{ selectedWord.exampleSentenceCn }}</div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { bgUrl } from '@/config/background.js'
import { fetchWordSummary, fetchWordDetail } from '@/utils/api.js'

const router = useRouter()
const route = useRoute()

// 从路由参数获取数据
const mode = ref(route.query.mode || 'learn')
const wordIds = ref(route.query.wordIds ? route.query.wordIds.split(',').map(id => parseInt(id)) : [])
const sessionId = ref(route.query.sessionId || '')

// 数据状态
const wordList = ref([])
const isLoading = ref(false)
const selectedWord = ref(null)
const completedCount = ref(0)
const remainingCount = ref(0)

// 获取单词小结数据
async function loadWordSummary() {
    try {
        isLoading.value = true
        // 首先尝试从sessionStorage获取（刚刚学习/复习过的单词）
        loadWordsFromSession()
        
        // 如果sessionStorage有数据，再尝试从API获取复习间隔等额外信息
        if (wordList.value.length > 0) {
            try {
                const data = await fetchWordSummary(wordIds.value, mode.value)
                if (data && data.words && Array.isArray(data.words)) {
                    // 合并API返回的数据（主要是nextReviewAt和统计信息）
                    const apiWordsMap = new Map(data.words.map(w => [w.wordId, w]))
                    wordList.value = wordList.value.map(word => {
                        const apiWord = apiWordsMap.get(word.wordId)
                        if (apiWord) {
                            return {
                                ...word,
                                nextReviewAt: apiWord.nextReviewAt || word.nextReviewAt,
                                // 保留API返回的其他信息
                                ...apiWord
                            }
                        }
                        return word
                    })
                    completedCount.value = data.completedCount || wordList.value.length
                    remainingCount.value = data.remainingCount || 0
                }
            } catch (apiError) {
                console.error('从API获取额外信息失败:', apiError)
                // API失败不影响，继续使用sessionStorage的数据
                completedCount.value = wordList.value.length
            }
        } else {
            // 如果sessionStorage没有数据，尝试从API获取
            const data = await fetchWordSummary(wordIds.value, mode.value)
            if (data && (data.words || Array.isArray(data))) {
                wordList.value = data.words || data || []
                completedCount.value = data.completedCount || wordList.value.length
                remainingCount.value = data.remainingCount || 0
            }
        }
    } catch (error) {
        console.error('获取单词小结失败:', error)
        // 如果都失败，至少尝试从sessionStorage获取
        if (wordList.value.length === 0) {
            loadWordsFromSession()
        }
    } finally {
        isLoading.value = false
    }
}

// 从sessionStorage加载单词数据
function loadWordsFromSession() {
    try {
        if (sessionId.value) {
            const sessionDataStr = sessionStorage.getItem(`study_session_${sessionId.value}`)
            if (sessionDataStr) {
                const sessionData = JSON.parse(sessionDataStr)
                // 使用保存的单词列表
                wordList.value = sessionData.wordList.map(word => ({
                    wordId: word.wordId,
                    word: word.word,
                    partOfSpeech: word.partOfSpeech,
                    correctMeaning: word.correctMeaning,
                    // 从复习记录中获取nextReviewAt（如果存在）
                    nextReviewAt: word.nextReviewAt || null,
                    phonetic: word.phonetic,
                    exampleSentenceEn: word.exampleSentenceEn,
                    exampleSentenceCn: word.exampleSentenceCn
                }))
                completedCount.value = wordList.value.length
                // remainingCount需要从后端获取，这里暂时设为0
                remainingCount.value = 0
            }
        }
    } catch (error) {
        console.error('从sessionStorage加载单词失败:', error)
        // 如果sessionStorage也失败，至少显示wordIds
        if (wordIds.value.length > 0) {
            wordList.value = wordIds.value.map(id => ({
                wordId: id,
                word: `单词 ${id}`,
                nextReviewAt: null
            }))
            completedCount.value = wordList.value.length
        }
    }
}

// 格式化复习间隔
function formatReviewInterval(nextReviewAt) {
    if (!nextReviewAt) return '待复习'
    
    try {
        const now = new Date()
        const reviewDate = new Date(nextReviewAt)
        const diffTime = reviewDate.getTime() - now.getTime()
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
        
        if (diffDays <= 0) {
            return '今天复习'
        } else if (diffDays === 1) {
            return '1天后复习'
        } else {
            return `${diffDays}天后复习`
        }
    } catch (error) {
        console.error('格式化复习间隔失败:', error)
        return '待复习'
    }
}

// 查看单词详情
async function viewWordDetail(word) {
    try {
        // 如果单词已经有详细信息，直接显示
        if (word.correctMeaning && word.partOfSpeech) {
            selectedWord.value = word
            return
        }
        
        // 否则从API获取详细信息
        const detail = await fetchWordDetail(word.wordId)
        selectedWord.value = { ...word, ...detail }
    } catch (error) {
        console.error('获取单词详情失败:', error)
        // 如果获取失败，至少显示已有信息
        selectedWord.value = word
    }
}

// 关闭单词详情
function closeWordDetail() {
    selectedWord.value = null
}

// 继续学习/复习
function continueStudy() {
    if (mode.value === 'learn') {
        router.push('/learn')
    } else {
        router.push('/review')
    }
}

// 返回首页
function backToHome() {
    router.push('/')
}

function noop() {}

onMounted(() => {
    loadWordSummary()
})
</script>

<style scoped>
.summary-screen {
    position: fixed;
    inset: 0;
    background-position: center;
    background-size: cover;
    background-repeat: no-repeat;
    color: #ffffff;
    display: flex;
    flex-direction: column;
}

.blur-overlay {
    position: absolute;
    inset: 0;
    backdrop-filter: blur(35px) brightness(0.95) saturate(1.05);
    -webkit-backdrop-filter: blur(35px) brightness(0.95) saturate(1.05);
    background: rgba(25, 35, 40, 0.25);
    z-index: 0;
}

.topbar {
    position: relative;
    z-index: 1;
    height: 56px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.back-btn {
    display: flex;
    align-items: center;
    justify-content: center;
}

.page-title {
    font-size: 18px;
    font-weight: 600;
    color: #ffffff;
    margin: 0;
}

.icon-btn {
    border: none;
    background: transparent;
    cursor: pointer;
    color: #e2e8f0;
    padding: 0;
    display: inline-flex;
    align-items: center;
    justify-content: center;
}

.summary-content {
    position: relative;
    z-index: 1;
    flex: 1;
    overflow-y: auto;
    padding: 16px 20px;
}

.tip-banner {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px 16px;
    background: rgba(255, 255, 255, 0.08);
    border-radius: 8px;
    margin-bottom: 16px;
    font-size: 14px;
    color: #cbd5e1;
}

.tip-icon {
    color: #fbbf24;
    flex-shrink: 0;
}

.word-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.word-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    background: rgba(255, 255, 255, 0.08);
    border-radius: 12px;
    cursor: pointer;
    transition: all 0.2s ease;
}

.word-item:hover {
    background: rgba(255, 255, 255, 0.12);
    transform: translateX(4px);
}

.word-text {
    font-size: 16px;
    font-weight: 500;
    color: #ffffff;
}

.review-interval {
    font-size: 14px;
    color: #94a3b8;
}

.loading, .empty-state {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 40px 20px;
}

.loading-text, .empty-text {
    font-size: 14px;
    color: #94a3b8;
}

.footer {
    position: relative;
    z-index: 1;
    padding: 16px 20px 24px;
    border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.progress-info {
    text-align: center;
    font-size: 14px;
    color: #94a3b8;
    margin-bottom: 16px;
}

.continue-btn {
    width: 100%;
    background: linear-gradient(135deg, #f59e0b 0%, #f97316 100%);
    color: #ffffff;
    border: none;
    border-radius: 12px;
    padding: 14px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
}

.continue-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(245, 158, 11, 0.3);
}

/* 单词详情弹窗 */
.word-detail-modal {
    position: fixed;
    inset: 0;
    background: rgba(0, 0, 0, 0.7);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
    padding: 20px;
}

.modal-content {
    position: relative;
    background: rgba(30, 41, 59, 0.95);
    border-radius: 16px;
    padding: 24px;
    max-width: 500px;
    width: 100%;
    max-height: 80vh;
    overflow-y: auto;
    backdrop-filter: blur(20px);
}

.close-btn {
    position: absolute;
    top: 16px;
    right: 16px;
    width: 32px;
    height: 32px;
    border: none;
    background: rgba(255, 255, 255, 0.1);
    color: #ffffff;
    border-radius: 50%;
    font-size: 24px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s ease;
}

.close-btn:hover {
    background: rgba(255, 255, 255, 0.2);
}

.modal-word {
    font-size: 24px;
    font-weight: 700;
    color: #ffffff;
    margin-bottom: 8px;
}

.modal-phonetic {
    font-size: 14px;
    color: #94a3b8;
    margin-bottom: 16px;
}

.modal-meaning {
    display: flex;
    align-items: flex-start;
    gap: 8px;
    margin-bottom: 16px;
    line-height: 1.6;
}

.modal-part-of-speech {
    font-size: 14px;
    color: #94a3b8;
    flex-shrink: 0;
}

.modal-meaning-text {
    font-size: 16px;
    color: #ffffff;
}

.modal-example {
    padding-top: 16px;
    border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.modal-example-en {
    font-size: 15px;
    color: #ffffff;
    margin-bottom: 8px;
    line-height: 1.6;
}

.modal-example-cn {
    font-size: 14px;
    color: #94a3b8;
    line-height: 1.6;
}
</style>

